<template>
  <div class="home_content">
    <Card :dx="10" :dy="80">
      <span class="jrink_title">Jrink</span>
      <el-progress :text-inside="true" :stroke-width="26" :percentage="processNum" />
      <el-button circle size="large" class="jrink_icon" :icon="MilkTea" @click="addProcessNum()"></el-button>
    </Card>
    <Card :dx="50" :dy="280" :dwidth="300" :dheight="100" style="padding: 10px; position: relative;">
      <div class="Date">
        <div an class="info-small">{{ currentDate }}</div>
        <div class="info-small">{{ lunarDay }}</div>
      </div>
      <div class="info-large">{{ currentTime }}</div>
    </Card>
    <Card :dx="100" :dy="300" :dwidth="200" :dheight="100" @click="goQuestion" class="Card">
      <div class="question">
        <div class="questionContent">{{ questionsContent }}</div>
        <div class="isCompleted"><el-checkbox label="今日已完成" name="type" disabled v-model="checkedNum" />
        </div>
      </div>
    </Card>
    <Card :dx="10" :dy="300" :dwidth="380" :dheight="200" class="Card">
      <div class="foodbox">
        <div class="foodTitle">今日饮食</div>

        <div class="meal_content">
          <div class="meal_img" :style="{ backgroundImage: `url(${LOGO})` }"></div>
          <div class="food_list_content">
            <div v-for="meal in currentMealList" class="foodList">
              <div>
                <span class="title">{{ meal.name }}:</span>
                <span v-for="item in foodList[meal.type]" :key="item.id">{{ foodDict[item.id] }}、</span>
              </div>
              <div class="add_button" @click="goFood(meal.type)">
                <el-icon> <Plus /> </el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Card>
  </div>
  <el-dialog
    v-model="dialogTableVisible"
    width="400px"
    title="请选择食谱"
  >
    <div class="food_list">
      <AddList ref="addListRef" :default-data="foodList[currentMealType]" query-type="recipe"></AddList>
    </div>
    <template #footer>
      <div class="dialog_footer">
        <el-button @click="dialogTableVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import Card from '@/components/card/index.vue'
import LOGO from '@/assets/cark.jpg'
import AddList from '@/components/addList/frontList.vue'
import { getLunar } from 'chinese-lunar-calendar'
import { ref, onMounted, onUnmounted } from 'vue'
import { MilkTea, Plus } from '@element-plus/icons-vue'
import { getQuestion, getRecordDay, updateByDateTime, getCookAll } from '@/views/database/questions/api';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

// 今天吃的食物集合
const foodList = ref([])
// 标题集合
const currentMealList = [
  { name: '早餐', type: 'm' },
  { name: '午餐', type: 'n' },
  { name: '晚餐', type: 'e' },
]
const foodDict = ref({}) // 反显食物用
// 添加食物的弹窗
const addListRef = ref(null)
// 添加食物的类型 m 早餐 n 午餐 e 晚餐
const currentMealType = ref('m');

const checkedNum = ref(false)
const questionRecord = ref(0)
const router = useRouter()
const currentTime = ref('');
const currentDate = ref(new Date().toLocaleDateString());
const lunarDay = ref('');
const dialogTableVisible = ref(false)
const tloading = ref(false)
const updateClock = () => {
  const now = new Date();
  const lunarDate = getLunar(now.getFullYear(), now.getMonth() + 1, now.getDate());
  // console.log(lunarDate)
  lunarDay.value = lunarDate.dateStr;
  // 获取当前时间并格式化为 HH:mm
  const options = { hour: '2-digit', minute: '2-digit', hour12: false, minimumIntegerDigits: 2 };
  currentTime.value = now.toLocaleTimeString(undefined, options);
};
const intervalId = setInterval(updateClock, 1000);

onMounted(() => {
  getFrontQuestion()
  getCookList()
  updateClock()
  getRecordDay().then(res => {
    questionRecord.value = res.result.question_number
    processNum.value = Number(res.result.jrink || 0)
    if (res.result.eat_list == null) {
      console.log('空空空');
    } else {
      foodList.value = JSON.parse(res.result.eat_list)
    }
    if (questionRecord.value >= 10) {
      checkedNum.value = true;
    }
  })
});
onUnmounted(() => {
  clearInterval(intervalId); // 清除定时器
});
const processNum = ref(0)
const addProcessNum = (num = 10) => {
  const newValue = processNum.value + num;
  if (newValue > 100) {
    // 如果超过 100，使用 Element Plus 的 Message 提示
    ElMessage({
      message: '饮水值已达标',
      type: 'warning'
    });
    // 将 processNum.value 限制在 100 以内
    processNum.value = 100;
  } else {
    // 否则正常增加
    processNum.value = newValue;
    updateByDateTime({ jrink: processNum.value })
  }
};
const goQuestion = () => {
  router.push({
    path: "/database/questionAnswer",
    query: { type: 1 }
  })
}
// 获取主页的题目
const questionsContent = ref({})
const getFrontQuestion = () => {
  const params = {
    number: 1
  };
  getQuestion(params).then(res => {
    // console.log('API 响应数据:', res.result);
    if (res.status === '1' && res.result && res.result.length > 0) {
      questionsContent.value = res.result[0].content;
    }
  });
}
// 弹出框框
const goFood = (type) => {
  dialogTableVisible.value = true
  currentMealType.value = type
}
const submitAdd = () => {
  // 将选中的食物添加进去
  const food_data = addListRef.value.getSelectData()
  const eat_data = { ...foodList.value }
  // 将选中食物添加到当前餐类型的数组中
  eat_data[currentMealType.value] = food_data.map(food => {
    return {
      id: food.id,
      weight: food.weight
    }
  })
  // 更新食物数据 本地和线上都改 省的要刷新
  foodList.value = JSON.parse(JSON.stringify(eat_data))
  console.log(eat_data, '更新数据==')
  updateByDateTime({ eat_list: JSON.stringify(eat_data) });
  // 关闭弹出框
  dialogTableVisible.value = false;
};

const getCookList = () => {
  // 查询所有食谱，生成 foodDict 用于
  tloading.value = true
  getCookAll().then(res => {
    tloading.value = false
    // cookList.value = res.result
    // 创建一个字典（键值对），用于存储食物id和对应的食物名称
    const foodMap = {};
    // 遍历接口返回的食谱列表
    res.result.forEach((food) => {
      // 将食物id作为键，食物名称作为值，存储在字典中
      foodMap[food.id] = food.name;
    })
    foodDict.value = foodMap
  })
}
</script>

<style lang="scss" scoped>
.home_content {
  background: url("@/assets/mian_bark.jpeg");
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
  height: calc(100vh - 60px);
  opacity: 0.8;

  .jrink_title {
    font-size: 24px;

  }

  .jrink_icon {
    font-size: large;
    position: absolute;
    top: 60px;
    right: -6px;
    border-right-color: gray;
  }
}

.DateDay {
  width: 100%;
  height: 100%;

}

.Date {
  text-align: left;
  width: 100px;
  display: flex;
  flex-direction: column;

}


.info-small {
  font-size: 18px;
  color: rgba(128, 128, 128, 1);
  /* 小字体 */
}

.info-large {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 60px;
  /* 大字体 */
}

.question {
  text-align: left;
  font-size: 20px;
  font-weight: bold;
  cursor: pointer;
  position: relative;
  white-space: pre-line;
}

.foodbox {
  font-size: 20px;
  max-width: 400px;
  cursor: pointer;
  text-align: left;

  .foodTitle {
    font-size: 23px;
    margin-bottom: 30px;
  }

  .meal_content {
    display: flex;
    .meal_img {
      width: 150px;
      height: 100px;
      border: 1px solid;
      background-size: contain;
      background-repeat: no-repeat;
    }

    .food_list_content {
      margin-left: 10px;
      flex: 1;
      font-size: 18px;
      .foodList {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: flex;
        justify-content: space-between;
        margin: 5px 0;

        .add_button {
          width: 25px;
          height: 25px;
          border-radius: 20px;
          text-align: center;
          line-height: 30px;
          font-size: 15px;
          font-weight: bold;
          margin-right: 5px;
          cursor: pointer;
          background: rgb(44, 85, 199);
          color: white;
        }
      }
    }
  }
}

.title {
  margin-right: 5px;
}

.isCompleted {
  position: absolute;
  top: 70px;
  left: 100px;
  color: #000;
}

.Card {
  padding: 10px;
  position: relative;
}

// 由于点击按钮也会变色无法解决暂时隐藏
// .Card:active {
//   background-color: beige;
// }
.food_list {
  display: flex;
  flex-wrap: wrap;

  ::v-deep .el-input__wrapper {
    border-radius: 20px;
  }
}


::v-deep .dialog_footer {
  display: flex;
}
</style>